package com.sand.service.Imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sand.dao.IBaseDao;
import com.sand.entity.*;
import com.sand.service.IAppoinService;
import com.sand.util.PageModel;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;


@Service(value = "apporinService")
public class AppoinServiceImp implements IAppoinService {
/**
 *
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/12/3/003 9:57
 */
    //Dao层接口
    @Resource(name = "baseDao")
    private IBaseDao baseDao;

    //根据id查询预约信息
    @Override
    public HashMap<String, Object> queryAppoinById(int id) {
        List<HashMap<String, Object>> list = baseDao.queryObject(" select new Map(" +
                "t1.rid as rid,t1.appointment as appointment,t1.status as status,t1.reservedCall as reservedCall," +
                "t2.buildingType as buildingType,t2.rentalType as rentalType,t2.paymentMethod as paymentMethod," +
                "t2.houseType as houseType,t2.floorSituation as floorSituation,t2.price as price,t2.houseDescribe as houseDescribe," +
                "t2.renovationCondition as renovationCondition,t3.communityName as communityName,t4.housePicture as housePicture," +
                "t5.browseNumber as browseNumber,t5.collectionNumber as collectionNumber,t6.phone as phone,t7.name as name,t8.parentId as parentId,t8.name as cityName) " +
                "from AppointmentformEntity t1 inner join HouseEntity t2 on t1.houseId=t2.rid " +
                "inner join CommunityEntity t3 on t2.communityId=t3.rid " +
                "inner join CityEntity t8 on t3.cityId=t8.rid " +
                "inner join HouseattachmentEntity t4 on t2.rid=t4.houseId " +
                "inner join HouserecordEntity t5 on t2.rid=t5.houseId " +
                "inner join UserinfoEntity t6 on t2.userId=t6.rid " +
                "inner join UserdetailsEntity t7 on t6.rid=t7.userId " +
                "where t4.isHouse=0 and t1.rid=?0", id);
        HashMap<String, Object> map = list.get(0);
        List<String> list3 = baseDao.queryObject("select t2.name as userName from AppointmentformEntity t1,UserdetailsEntity t2 where t1.userId=t2.userId and t1.rid=?0", id);
        map.put("userName",list3.get(0));
        List<String> list1 = baseDao.queryObject("select t1.name from CityEntity t1 where t1.rid=?0", Integer.parseInt(map.get("parentId").toString()));
        map.put("cityNamePro",list1.get(0));

        return map;
    }

    //分页查询预约信息
    @Override
    public PageModel<HashMap<String, Object>> queryAppoinLimit(int limit, int page, String condition) {
        PageModel<HashMap<String, Object>> pm = new PageModel<HashMap<String, Object>>();

        //计算开始位置
        int begin=(page-1)*limit;
        //创建查询对象
        DetachedCriteria dc = DetachedCriteria.forClass(AppointmentformEntity.class);
        //添加模糊查询条件
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);
            if(obj.get("status")!=null && !"".equals(obj.get("status"))){
                dc.add(Restrictions.eq("status",obj.get("status").toString()));
            }
            if(obj.get("comName")!=null && !"".equals(obj.get("comName"))){
                List list = baseDao.queryObject("select t1.rid from HouseEntity t1 inner join CommunityEntity t2 on t1.communityId=t2.rid inner join HouserecordEntity t3 on t1.rid=t3.houseId where t3.auditStatus='审核通过' and t2.communityName like '%"+obj.get("comName").toString()+"%'");
                dc.add(Restrictions.in("houseId",list));
            }
        }

        List<Long> list1 = baseDao.queryObjectCommon(dc.setProjection(Projections.rowCount()));
        dc.setProjection(null);
        dc.setProjection(Projections.property("rid"));
        dc.addOrder(Order.desc("rid"));
        List list = baseDao.queryObjectLimit(dc, begin, limit);
        long i=list1.get(0);
        int count= (int) i;

        List<HashMap<String, Object>> list2 = baseDao.queryObject(" select new Map(" +
                "t1.rid as rid,t1.appointment as appointment,t1.status as status,t5.name as name," +
                "t3.communityName as communityName,t2.buildingType as buildingType,t4.name as cityName) " +
                "from UserdetailsEntity t5, AppointmentformEntity t1 inner join HouseEntity t2 on t1.houseId=t2.rid " +
                "inner join CommunityEntity t3 on t2.communityId=t3.rid " +
                "inner join CityEntity t4 on t3.cityId=t4.rid where t2.userId=t5.userId and t1.rid in (?0)", list);

        for (HashMap<String, Object> map : list2) {
            List<String> list3 = baseDao.queryObject("select t2.name as userName from AppointmentformEntity t1,UserdetailsEntity t2 where t1.userId=t2.userId and t1.rid=?0", Integer.parseInt(map.get("rid").toString()));
            map.put("userName",list3.get(0));
        }

        pm.setList(list2);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);
        return pm;
    }
    //根据用户查询所有预约信息
    @Override
    public List<HashMap<String, Object>> queryAppoinByUserInfo(int id) {
        return null;
    }

    //添加预约信息
    @Override
    public boolean addAppoin(String data) {
        //创建时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        if(data!=null){
            AppointmentformEntity add = JSON.parseObject(data, AppointmentformEntity.class);
            add.setAppointment(add.getAppointment().replaceFirst("~","-"));
            //添加预约
            boolean b = baseDao.addObject(add);
            if(!b){
                return false;
            }
            //预约成功添加对话
            //房东id
            List<Integer> list = baseDao.queryObject("select t1.userId from HouseEntity t1 where t1.rid=?0", add.getHouseId());
            int j=list.get(0);
            //对话信息查询
            List<MessageEntity> msgList = baseDao.queryObject("from MessageEntity t1 where t1.userId=?0 and t1.landlordId=?1", add.getUserId(), j);
            if(msgList==null || msgList.size()<=0){
                //添加对话
                MessageEntity msg = new MessageEntity();
                msg.setUserId(add.getUserId());
                msg.setLandlordId(j);
                msg.setLastChatTime(timestamp);
                msg.setLastChatMessage("你好,我刚才预约了您看房 ~");
                baseDao.addObject(msg);
                MessagedetailsEntity msgs = new MessagedetailsEntity();
                msgs.setTime(timestamp);
                msgs.setUserId(add.getUserId());
                msgs.setContent("你好,我刚才预约了您看房 ~");
                msgs.setMessageId(msg.getRid());
                baseDao.addObject(msgs);
            }else{
                MessageEntity msg = msgList.get(0);
                msg.setLastChatMessage("你好,我刚才预约了您看房 ~");
                msg.setLastChatTime(timestamp);
                baseDao.updateObject(msg);
                MessagedetailsEntity msgs = new MessagedetailsEntity();
                msgs.setTime(timestamp);
                msgs.setUserId(add.getUserId());
                msgs.setContent("你好,我刚才预约了您看房 ~");
                msgs.setMessageId(msg.getRid());
                baseDao.addObject(msgs);
            }
            return true;
        }
        return false;
    }
    //删除预约信息
    @Override
    public boolean delAppoin(int rid,String condition,int isHouse) {
        //创建时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        List<AppointmentformEntity> list = baseDao.queryObject("from AppointmentformEntity t1 where t1.rid=?0", rid);
        AppointmentformEntity app = list.get(0);
        boolean bln = baseDao.delObject(app);
        if(!bln){
            return false;
        }
        //房东id
        List<Integer> list1 = baseDao.queryObject("select t1.userId from HouseEntity t1 where t1.rid=?0", app.getHouseId());
        int j=list1.get(0);
        //对话信息查询
        List<MessageEntity> msgList = baseDao.queryObject("from MessageEntity t1 where t1.userId=?0 and t1.landlordId=?1", app.getUserId(), j);
        if(msgList!=null && msgList.size()>0){
            //添加通知
            MessageEntity msg = msgList.get(0);
            msg.setLastChatTime(timestamp);
            msg.setLastChatMessage(condition);
            //发送取消预约通知
            MessagedetailsEntity msgs = new MessagedetailsEntity();
            msgs.setMessageId(msg.getRid());//可以更改为系统通知
            msgs.setTime(timestamp);
            msgs.setContent(condition);
            switch (isHouse){
                case 1://房东取消预约
                    msgs.setUserId(msg.getLandlordId());

                    break;
                case 0://租客取消预约
                    msgs.setUserId(msg.getUserId());
                    break;
            }
            baseDao.addObject(msgs);
            baseDao.updateObject(msg);
        }
        return true;
    }
    //修改预约信息
    @Override
    public boolean updateAppoin(int rid) {
        List<AppointmentformEntity> list = baseDao.queryObject("from AppointmentformEntity t1 where t1.rid=?0",rid);
        AppointmentformEntity app = list.get(0);
        app.setStatus("已看房");
        boolean bln = baseDao.updateObject(app);
        if(bln)return true;
        return false;
    }
    /**
     * 房东房屋预约记录
     * @param limit
     * @param page
     * @param condition
     * @return
     */
    @Override
    public PageModel<HashMap<String, Object>> queryAppointByUserIdLimit(int limit, int page, String condition) {
        PageModel<HashMap<String, Object>> pm = new PageModel<>();
        //分页开始的位置
        page = (page-1)*limit;
        //创建查询对象
        DetachedCriteria criteria = DetachedCriteria.forClass(AppointmentformEntity.class);
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);
            if(obj.get("userId")!=null){
                List list=baseDao.queryObject("select t1.rid from HouseEntity t1 where t1.userId = ?0",Integer.parseInt(obj.get("userId").toString()));
                criteria.add(Restrictions.in("houseId",list));
            }
        }

        List<Long> list1 = baseDao.queryObjectCommon(criteria.setProjection(Projections.rowCount()));

        criteria.setProjection(null);

        //rid的集合
         criteria.setProjection(Projections.property("rid"));

        criteria.addOrder(Order.desc("rid"));

        //查询到所有
        List list = baseDao.queryObjectLimit(criteria, page, limit);

        long i=list1.get(0);

        int count= (int) i;

        //查询预约记录信息
        List<HashMap<String, Object>> list3 = baseDao.queryObject("select new Map(" +
                "t1.rid as rid,t1.userId as userId,t1.paymentMethod as paymentMethod,t1.buildingType as buildingType," +
                "t1.houseType as houseType,t1.renovationCondition as renovationCondition,t1.towards as towards," +
                "t1.housingConfiguration as housingConfiguration,t2.communityName as communityName," +
                "t2.communityAddress as communityAddress,t6.userId as userId,t6.rid as appoinId,t6.appointment as appointment,t6.status as status," +
                "t5.name as name,t3.housePicture as housePicture) " +
                "from HouseEntity t1 inner join HouseattachmentEntity t3 on t1.rid=t3.houseId " +
                "inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                "inner join AppointmentformEntity t6 on t1.rid=t6.houseId " +
                "inner join CityEntity t5 on t2.cityId=t5.rid " +
                "where t3.isHouse=0 and t6.rid in(?0) group by t1.rid", list);


        pm.setList(list3);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);

        return pm;
    }


}